﻿using System;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;

namespace Torrenter.Client.Main.objects
{
    public sealed class NotifyTraceListener : TraceListener, INotifyPropertyChanged
    {
        private static readonly NotifyTraceListener instance = new NotifyTraceListener();
        private string log;

        public event PropertyChangedEventHandler PropertyChanged;

        public string Log
        {
            get
            {
                return log;
            }
            set
            {
                log = value;
                RaisePropertyChanged("Log");
            }
        }

        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static NotifyTraceListener()
        {
            Trace.Listeners.Add(instance);
        }

        private NotifyTraceListener()
        {
        }

        public static NotifyTraceListener Instance
        {
            get
            {
                return instance;
            }
        }

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public override void Write(string message)
        {
            //Log += string.Format("[{0}] {1}", DateTime.Now.ToString(), message);
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("[{0}] {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), message);
            sb.Append(log);
            Log = sb.ToString();
        }

        public override void WriteLine(string message)
        {
            Write(message + Environment.NewLine);
        }
    }

    public sealed class TraceCategory
    {
        public static readonly string Action = "Action";
        public static readonly string Exception = "Exception";
        public static readonly string Test = "Test";
        public static readonly string System = "System";
    }
}
